package com.tanhua.admin.controller;

import cn.hutool.core.date.DateUtil;
import com.tanhua.admin.service.AnalysisService;
import com.tanhua.model.chart.ChartDateVo;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.vo.AnalysisSummaryVo;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

@RestController
@RequestMapping("/dashboard")
public class DashboardController {
    @Autowired
    private AnalysisService analysisService;
    /**
     * 概要统计信息
     * @return
     */
    @GetMapping("/summary")
    public AnalysisSummaryVo getSummary() throws ParseException {
        /**
         * 由于数据表 2020-09-25 是最新时间
         * 设定 now 为数据表最新时间
         */
        //创建返回对象Vo
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();
        /*创建实时时间
        Date now = Calendar.getInstance().getTime();*/
        String day = "2020-09-25";
        //定义转换格式
        SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
        //调用formatter.parse(),将"19570323"转化为date类型  输出为：Fri Sep 25 00:00:00 CST 2020
        Date now = formatter.parse(day);
        /**
         * 累计用户数
         * Analysis表，查询表中注册用户的总和
         */
        Integer total = analysisService.queryCumulativeUsers();
        analysisSummaryVo.setCumulativeUsers(Long.valueOf(total));
        /**
         * 查询今日统计信息
         */
        Analysis today_analysis = analysisService.querySummary(now);
        /**
         * 查询过去30天活跃用户--查询今日统计信息中num_active30天和
         */
        analysisSummaryVo.setActivePassMonth(Long.valueOf(today_analysis.getGetNumActive30()));
        /**
         * 查询过去7天活跃用户--查询今日统计信息中num_active7天和
         */
        analysisSummaryVo.setActivePassMonth(Long.valueOf(today_analysis.getGetNumActive7()));
        /**
         * 查询今日活跃用户--tb_log表查询
         */
        analysisSummaryVo.setActiveUsersToday(Long.valueOf(today_analysis.getNumActive()));
        /**
         * 今日新增用户
         */
        analysisSummaryVo.setNewUsersToday(Long.valueOf(today_analysis.getNumRegistered()));
        /**
         * 今日登录用户
         */
        analysisSummaryVo.setLoginTimesToday(Long.valueOf(today_analysis.getNumLogin()));
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        /**
         * 查询昨日统计信息
         */
        Analysis yestoday_analysis = analysisService.querySummary(DateUtils.addDays(now, -1));

        //注册用户涨跌率，单位百分数，正数为涨，负数为跌
        analysisSummaryVo.setNewUsersTodayRate(computeRate(Long.valueOf(today_analysis.getNumRegistered()), Long.valueOf(yestoday_analysis.getNumRegistered())));

        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        analysisSummaryVo.setLoginTimesTodayRate(computeRate(Long.valueOf(today_analysis.getNumLogin()), Long.valueOf(yestoday_analysis.getNumLogin())));

        //活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        analysisSummaryVo.setActiveUsersTodayRate(computeRate(Long.valueOf(today_analysis.getNumActive()), Long.valueOf(yestoday_analysis.getNumActive())));

        return analysisSummaryVo;
    }
    //计算比率
    private static BigDecimal computeRate(Long current,Long last){
        BigDecimal result;
        if (last == 0){
            //如果上次为0，则本次增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        }else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
    //？啥作用？
    private static String offsetDay(Date date, int offSet) {
        return DateUtil.offsetDay(date, offSet).toDateStr();
    }

    /**
     * 新增、活跃用户、次日留存率
     */
    @GetMapping("/users")
    public ChartDateVo getUserDate(@RequestParam String type,@RequestParam String sd,@RequestParam String ed) {
        //接收前端时间戳，转化为UTC北京标准时间
        String[] backEnd_time = timeStampFormat(sd,ed);
        ChartDateVo chartDateVo = analysisService.queryBasicStatistics(backEnd_time, type);
        return chartDateVo;
    }

    /**
     * 时间格式转化
     * @param time
     * @return
     */
    public String[] timeStampFormat(String... time){
        //先对数组进行排序
        Arrays.sort(time);
        //新建一个数组
        String[] formatTime = new String[4];
        //遍历数组
        for (int i = 0; i < time.length; i++) {
            //制作Date时间戳
            Date thisYear_Date = new Date(Long.parseLong(time[i]));
            //创建Calendar实例，准备制作对应时间的上年时间
            Calendar calendar = Calendar.getInstance();
            //得到上年时间lastYear_Date
            calendar.setTime(thisYear_Date);
            calendar.add(Calendar.YEAR, -1);
            Date lastYear_Date = calendar.getTime();
            //开始转化
            //制作转化格式 Locale.CHINA表示转化为北京标准时区
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            //转化时间
            String thisYear = format.format(thisYear_Date);
            String lastYear = format.format(lastYear_Date);
            //构建返回数组
            for (int j = 0; j < formatTime.length; j++) {
                formatTime[i] = thisYear;
                formatTime[i+2] = lastYear;
            }
        }
        return formatTime;
    }
}
